// vuedemo/src/api/user.ts
import request from "@/utils/request";

interface LoginData {
  username: string;
  password: string;
}

interface RegisterData extends LoginData {
  gender: number;
  job: number;
  phone: string;
}

interface LoginResponse {
  code: number;
  msg: string;
  data?: {
    token: string;
    username: string;
  };
}

// 登录接口
export function login(data: LoginData) {
  return request({
    url: "/users/login",
    method: "post",
    data: data,
  }).then((res) => {
    // res.data 才是实际的响应数据
    const response = res.data as LoginResponse;
    if (response.code === 1 && response.data) {
      return {
        code: response.code,
        msg: response.msg,
        data: {
          token: response.data.token,
          username: response.data.username
        }
      };
    }
    // 提供更友好的错误信息
    if (response.msg && response.msg.includes("用户名不存在")) {
      throw new Error("用户名不存在，请检查您的输入或注册新账号");
    } else if (response.msg && response.msg.includes("密码错误")) {
      throw new Error("密码错误，请重新输入");
    } else {
      throw new Error(response.msg || "登录失败，请稍后再试");
    }
  });
}

// 注册接口
export function register(data: RegisterData) {
  return request({
    url: "/users/register",
    method: "post",
    data: {
      username: data.username,
      password: data.password,
      gender: data.gender || 1,
      job: data.job || 4,
      phone: data.phone,
      name: data.username,
      createTime: new Date(),
      updateTime: new Date(),
    },
  }).then((res) => {
    // 确保返回的是直接可用的响应数据
    return res.data;
  });
}